package cn.edu.hhu.teacher;

import cn.edu.hhu.teacher.bean.Teacher;
import cn.edu.hhu.teacher.service.TeacherService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/teacher/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //校验验证码
        String input_verifycode = request.getParameter("verifycode");
        String true_verifycode = (String) request.getSession().getAttribute("verifycode");
        if (true_verifycode == null || !true_verifycode.equalsIgnoreCase(input_verifycode)) {
            request.setAttribute("msg", "验证码错误！");
            request.getRequestDispatcher("/WEB-INF/view/teacher/login.jsp").forward(request, response);
            return;
        }
        //封装Teacher对象
        Map<String, String[]> map = request.getParameterMap();
        Teacher teacher = new Teacher();
        try {
            BeanUtils.populate(teacher, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service
        TeacherService teacherService = new TeacherService();
        Teacher loginTeacher = teacherService.login(teacher);
        //判断是否登录成功
        if (loginTeacher != null && loginTeacher.isActivation()) {
            //登陆成功
            request.getSession().setAttribute("teacher", loginTeacher);
            String uri = (String) request.getSession().getAttribute("fromuri");
            if (uri != null) {
                request.getSession().removeAttribute("fromuri");
                response.sendRedirect(uri);
            } else {
                response.sendRedirect(request.getContextPath() + "/teacher/index");
            }
        } else {
            //登陆失败
            request.setAttribute("msg", "工号或密码错误！");
            request.getRequestDispatcher("/WEB-INF/view/teacher/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/view/teacher/login.jsp").forward(request, response);
    }
}
